#include "ActiveTarget.h"

using namespace scalp;

CActiveTarget::CActiveTarget(CFunction<void(void)>* aCancelCallback, CFunction<TInt(TInt)>* aRunErrorCallback, const TPriority& aPriority) : CActive(aPriority), iCancelCallback(aCancelCallback), iRunErrorCallback(aRunErrorCallback)
	{
	CActiveScheduler::Add(this);
	}

CFunction<void(void)>* CActiveTarget::AppendRunL( CFunction<void(void)>* aCallback)
	{
	iRunLCallbackArray.AppendL(aCallback);
	return aCallback;
	}
CActiveTargetConnection* CActiveTarget::AppendRunConnectionL( CFunction<void(void)>* aCallback)
	{
	iRunLCallbackArray.AppendL(aCallback);
	return new (ELeave) CActiveTargetConnection(this, aCallback);
	}
void CActiveTarget::SetCancel( CFunction<void(void)>* aCallback)
	{
	delete iCancelCallback;
	iCancelCallback = aCallback;
	}
void CActiveTarget::SetRunError( CFunction<TInt(TInt)>* aCallback)
	{
	delete iRunErrorCallback;
	iRunErrorCallback = aCallback;	
	}
CActiveTarget::~CActiveTarget()
	{
	Cancel();
	delete iCancelCallback;
	delete iRunErrorCallback;	
	for(TInt i = 0 ; i < iRunLCallbackArray.Count() ; ++i)
		delete iRunLCallbackArray[i];
	iRunLCallbackArray.Close();
	}


void CActiveTarget::RunL()
	{
	for(TInt i = 0 ; i < iRunLCallbackArray.Count() ; ++i)
		(*iRunLCallbackArray[i])();
	}
TInt CActiveTarget::RunError(TInt aError)
	{
	if(iRunErrorCallback)
		return (*iRunErrorCallback)(aError);
	return CActive::RunError(aError);
	}
void CActiveTarget::DoCancel()
	{
	if(iCancelCallback)
		(*iCancelCallback)();
	}

CActiveTargetConnection::CActiveTargetConnection(CActiveTarget* aActiveTarget, CFunction<void(void)>* aCallback) : iActiveTarget(aActiveTarget), iCallback(aCallback)
	{
	}
CActiveTargetConnection::~CActiveTargetConnection()
	{
	for(TInt i = 0 ; i < iActiveTarget->iRunLCallbackArray.Count() ; ++i)
		if(iActiveTarget->iRunLCallbackArray[i] == iCallback)
			{
			delete iCallback;
			iActiveTarget->iRunLCallbackArray.Remove(i);
			--i;
			}
	}

